﻿using HBase.db;
using hCommand;
using System;
using System.Security.Cryptography;

namespace Persistence {
    public class CsdSaveEngine : GkTransaction {
        public CoreStockDet csd;
        //status count  doiType  itemId
        protected override TransRes Execute() {
            WhDoiDet doiDet = getById<WhDoiDet>(csd.doiDetId); 
            doiInfo(csd);
          
            if (csd.barCode == null) {
                csd.barCode = "";
            } 
            CoreItem item = getById<CoreItem>(csd.itemId);
            if (csd.id == 0) { 
                if (item.fenlei == 1) {
                    double count = csd.countDb;
                    csd.countDb = 1;
                    BParam p = getById<BParam>(12);
                    long begin = p.v;
                    for (int i = 0; i < count; i++) {
                        CoreStockDet det = (CoreStockDet)csd.Clone();
                        det.barCode = "" + begin++;
                        insert(det);
                    }
                    p.v = begin;
                    update(p);
                } else {
                    insert(csd);
                }
            } else {
                update(csd);
            }
            doiActive( csd.doiDetId, doiDet.planCount); 
            return new TransRes();
        }
         public void doiActive( long id,double max) {
            if (id == 0) {
                return;
            } 
            String sqlsum = "select sum(count_db) from (SELECT count_db FROM `d_stock_det1` a where a.doi_det_Id=@id  union all SELECT count_db FROM `core_stock_det`  b where b.doi_det_Id=@id) c ";
            double sum = queryUnique<double>(sqlsum, new { id });
            sum = CsdUtil.Round(sum);

            if (max < sum) {
                throw  new Exception("实际大于计划数量");
            }
            string sql1 = $@"update Wh_Doi_det set  active_Count=@sum where id=@id ";
            exec(sql1, new { id, sum });

            String sql = "update wh_doi set status=2 where id= (SELECT pid FROM wh_doi_det  where id=@id and   active_Count>0)";
            exec(sql, new { id });

        }

        void doiInfo(CoreStockDet csd) {
            WhDoiDet det = getById<WhDoiDet>(csd.doiDetId);
            if (det != null) {
                WhDoi doi = getById<WhDoi>(det.pid);
                csd.batchNo = doi.batchNo;
                csd.doiType = DetConst.DoiTypeDj;
                csd.unit = det.unit;
                csd.itemId = det.itemId;
            }
        }
     

       
    }
}
